package com.nuoniu.sibanyun.service.crm.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.crm.CrmCustomer;
import com.nuoniu.sibanyun.entity.crm.CrmStrategy;
import com.nuoniu.sibanyun.entity.crm.CrmTouch;
import com.nuoniu.sibanyun.entity.dto.CrmTouchSvaeDto;
import com.nuoniu.sibanyun.mapper.crm.CrmTouchMapper;
import com.nuoniu.sibanyun.service.crm.ICrmCustomerService;
import com.nuoniu.sibanyun.service.crm.ICrmStrategyService;
import com.nuoniu.sibanyun.service.crm.ICrmTouchService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.xmlconfig.Usertypeconfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 * 联系记录 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-06-15
 */
@Service
public class CrmTouchServiceImpl extends ServiceImpl<CrmTouchMapper, CrmTouch> implements ICrmTouchService {

    @Autowired
    private ICrmTouchService touchService;
    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    private ICrmStrategyService crmStrategyService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveCrmTouche(CrmTouchSvaeDto touchSaveDto) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer crmCustomerStatus = crmCustomerService.getCrmCustomerStatus(touchSaveDto.getCrmId());
        if( null == crmCustomerStatus || 0 != crmCustomerStatus){
            throw new NuoNiuException("客户信息状态异常，请刷新后重试，或者联系管理员");
        }

        CrmTouch crmTouch = new CrmTouch();
        BeanUtils.copyProperties(touchSaveDto,crmTouch);
        if(crmTouch.getId() == null) {
            crmTouch.setCompanyId(userInfo.getCompanyId());
            crmTouch.setCreateUserId(userInfo.getUserId());
            crmTouch.setCreateUserName(userInfo.getRealName());
//            crmTouch.setPhotograph(null);
//            crmTouch.setVisitSign(null);
//            if(StringUtils.isNotBlank(touchSaveDto.getCrmGrade())) { //修改客户的等级
//                Integer count = baseMapper.getMaxTouchCount(crmTouch.getContactDate(), userInfo.getCompanyId());
//                if(count >= 1) {
//                    CrmCustomer crmCustomer = new CrmCustomer();
//                    crmCustomer.setId(touchSaveDto.getCrmId().longValue());
//                    crmCustomer.setCrmGrade(touchSaveDto.getCrmGrade());
//                    crmCustomerService.updateById(crmCustomer);
//                }
//            }

            if(touchSaveDto.getType() != null && touchSaveDto.getType().equals(2)) {
                crmTouch.setContactDate(LocalDate.now());
            }
        }else {
            //获取 客户策略
            CrmStrategy crmStrategy = crmStrategyService.getStrategyByCode("crm_7", userInfo.getCompanyId());
            String strategyVal = crmStrategy.getStrategyVal();
            Integer maxHours = 0;
            if(StringUtils.isNotBlank(strategyVal)){
                try {
                    maxHours = Integer.valueOf(strategyVal);
                }catch (Exception e){
                    throw new NuoNiuException("联系记录修改策略错误，请联系管理员");
                }
            }

            CrmTouch touch = touchService.getById(crmTouch.getId());
            LocalDateTime createDate = touch.getCreateDate();
            long hours = Duration.between(createDate, LocalDateTime.now()).toHours();
            if(maxHours > 0 && hours > maxHours){
                throw new NuoNiuException("修改失败,联系记录信息已经超过" + maxHours + "小时，不能修改");
            }
        }

        crmTouch.setUpdateDate(LocalDateTime.now());
        crmTouch.setUpdateUserId(userInfo.getUserId());
        crmTouch.setUpdateUserName(userInfo.getRealName());

        boolean update = touchService.saveOrUpdate(crmTouch);
        //更新 客户表的 上次联系时间 和 下次联系时间
        if(update){
            CrmCustomer crmCustomer = new CrmCustomer();
            if(null != crmTouch.getCrmId() && null != crmTouch.getContactDate()){
                crmCustomer.setLastTouchDate(crmTouch.getContactDate().atStartOfDay());
                if(null != crmTouch.getNextTouchDate()){
                    crmCustomer.setNextTouchDate(crmTouch.getNextTouchDate());
                }

                String lastTouchSummary = com.nuoniu.sibanyun.common.lang.StringUtils.subStringBeforeAppointChars(crmTouch.getRemarks(),"。","？","！","?","!");
                if(StringUtils.isNotBlank(lastTouchSummary) && lastTouchSummary.length() > 250){
                    lastTouchSummary = StringUtils.substring(crmTouch.getRemarks(),0,250);
                }else if(StringUtils.isNotBlank(lastTouchSummary) && lastTouchSummary.length() == 0){
                    lastTouchSummary = StringUtils.substring(crmTouch.getRemarks(),0,20);
                }

                crmCustomer.setLastTouchSummary(lastTouchSummary);
                QueryWrapper<CrmCustomer> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id",crmTouch.getCrmId());
                queryWrapper.and(wrapper -> wrapper.isNull("last_touch_date").or().lt("last_touch_date",crmTouch.getContactDate()));
                crmCustomerService.update(crmCustomer,queryWrapper);
            }
        }
    }

    @Override
    public Page<CrmTouch> pageList(Page page, CrmTouch touch) {
        UserInfo userInfo = UserThreadLocal.get();
        touch.setCompanyId(userInfo.getCompanyId());
        return baseMapper.pageList(page, touch);
    }

    @Override
    @Transactional
    public void disable(String ids) {
        UserInfo userInfo = UserThreadLocal.get();
        if (StringUtils.isNoneBlank(ids)) {
            //获取 客户策略
            CrmStrategy crmStrategy = crmStrategyService.getStrategyByCode("crm_7", userInfo.getCompanyId());
            String strategyVal = crmStrategy.getStrategyVal();
            for (String id : ids.split(",")) {
                Integer maxHours = 0;
                if(StringUtils.isNotBlank(strategyVal)){
                    try {
                        maxHours = Integer.valueOf(strategyVal);
                    }catch (Exception e){
                        throw new NuoNiuException("联系记录删除策略错误，请联系管理员");
                    }
                }

                CrmTouch touch = touchService.getById(id);
                LocalDateTime createDate = touch.getCreateDate();
                long hours = Duration.between(createDate, LocalDateTime.now()).toHours();
                if(maxHours > 0 && hours > maxHours){
                    throw new NuoNiuException("联系记录信息已经超过" + maxHours + "小时，不能删除");
                }

                CrmTouch crmTouch = new CrmTouch();
                crmTouch.setId(Long.valueOf(id));
                crmTouch.setStatus(2);
                touchService.updateById(crmTouch);
            }
        }
    }
}
